package com.sinochem.sales.service.controller;

import com.luhuiguo.fastdfs.domain.StorePath;
import com.luhuiguo.fastdfs.service.FastFileStorageClient;
import com.sinochem.sales.common.api.to.sms.FileTO;
import com.sinochem.sales.common.api.vo.AttachmentFileVO;
import com.sinochem.sales.common.entity.Result;
import com.sinochem.sales.common.enums.EnabledStatusEnum;
import com.sinochem.sales.common.exception.BusinessException;
import com.sinochem.sales.common.util.AssertUtils;
import com.sinochem.sales.common.util.UserUtils;
import com.sinochem.sales.service.config.FdfsPropertiesConfig;
import com.sinochem.sales.service.service.IAttachmentFileService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.sagacity.sqltoy.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * @author xuan😴🐶🐱🐽🌺  <a href="zhangshixuanj@163.com">联系作者</a>
 * @version Revision:v1.0,Date: 2018/4/16 14:30
 * @project sinochem-ubmp-registry
 * @description
 * @Modification Date: 2018/4/16 14:30  {填写修改说明}
 */
@Slf4j
@RestController
@RequestMapping("file")
@Api(tags = "文件操作")
public class FileController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private IAttachmentFileService attachmentFileService;

    @Autowired
    private FdfsPropertiesConfig fdfsPropertiesConfig;


    /**
     * uploadByType
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<FileTO> upload(@RequestParam("file") MultipartFile file) {
        FileTO fileTO = new FileTO();
        // 判断图片是否为空
        if (file.isEmpty()) return Result.error("图片为空");
        // 获取图片
        String originalFilename = file.getOriginalFilename();
        // ext .
        String extName = extName(originalFilename);
        AttachmentFileVO attachmentFileVO = new AttachmentFileVO();
        attachmentFileVO.setFileName(originalFilename);
        attachmentFileVO.setFileExtName(extName);
        try {
            //up
            StorePath storePath = fastFileStorageClient.uploadFile(file.getBytes(), extName);
            attachmentFileVO.setFileGroupId(storePath.getGroup());
            attachmentFileVO.setSaveName(storePath.getPath());
            String filePath = fdfsPropertiesConfig.getFileHost() + storePath.getFullPath();
            attachmentFileVO.setFilePath(filePath);
            attachmentFileVO.setEnabled(EnabledStatusEnum.Enabled.value());
            attachmentFileVO.setCreateTime(DateUtil.getNowTime());
            attachmentFileVO.setBizType("default");
            attachmentFileVO.setCreateBy(StringUtils.isEmpty(UserUtils.getUID()) ? "default" : UserUtils.getUID());
            //add
            attachmentFileVO = attachmentFileService.addAttachmentFile(attachmentFileVO);
            if (null != attachmentFileVO && !StringUtils.isEmpty(attachmentFileVO.getFileId())) {
                // 图片地址
                fileTO.setFilePath(filePath);
                // 图片id
                fileTO.setFileId(attachmentFileVO.getFileId());
                // ext扩展
                fileTO.setFileExtName(extName);
            } else {
                //TODO 队列删除
                throw new BusinessException("上传文件失败");
            }
        } catch (IOException e) {
            return Result.error("上传文件失败");
        }

        return Result.success(fileTO);
    }

    /**
     * uploadByType
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadByType")
    public Result<FileTO> uploadByType(@RequestParam("file") MultipartFile file, @RequestParam("bizType") String bizType) {
        FileTO fileTO = new FileTO();
        // 判断文件是否为空
        if (file.isEmpty()) return Result.error("文件为空");
        // 获取文件
        String originalFilename = file.getOriginalFilename();
        // ext .
        String extName = extName(originalFilename);
        AttachmentFileVO attachmentFileVO = new AttachmentFileVO();
        attachmentFileVO.setFileName(originalFilename);
        attachmentFileVO.setFileExtName(extName);
        try {
            //up
            StorePath storePath = fastFileStorageClient.uploadFile(file.getBytes(), extName);
            attachmentFileVO.setFileGroupId(storePath.getGroup());
            attachmentFileVO.setSaveName(storePath.getPath());
            String filePath = fdfsPropertiesConfig.getFileHost() + storePath.getFullPath();
            attachmentFileVO.setFilePath(filePath);
            attachmentFileVO.setEnabled(EnabledStatusEnum.Enabled.value());
            attachmentFileVO.setCreateTime(DateUtil.getNowTime());
            attachmentFileVO.setBizType(bizType);
            attachmentFileVO.setCreateBy(StringUtils.isEmpty(UserUtils.getUID()) ? "default" : UserUtils.getUID());
            //add
            attachmentFileVO = attachmentFileService.addAttachmentFile(attachmentFileVO);
            if (null != attachmentFileVO && !StringUtils.isEmpty(attachmentFileVO.getFileId())) {
                // 图片地址
                fileTO.setFilePath(filePath);
                // 图片id
                fileTO.setFileId(attachmentFileVO.getFileId());
                // ext扩展
                fileTO.setFileExtName(extName);
            } else {
                //TODO 队列删除
                throw new BusinessException("上传文件失败");
            }
        } catch (IOException e) {
            return Result.error("上传文件失败");
        }

        return Result.success(fileTO);
    }

    /**
     * download
     *
     * @return
     */
    @PostMapping("/download")
    public Result<byte[]> download(@RequestParam("fileId") String fileId) {
        if (StringUtils.isEmpty(fileId)) {
            return Result.error("未找到文件");
        }
        AttachmentFileVO attachmentFileVO = new AttachmentFileVO();
        attachmentFileVO.setFileId(fileId);
        attachmentFileVO = attachmentFileService.loadAttachmentFile(attachmentFileVO);
        byte[] fileBytes = fastFileStorageClient.downloadFile(attachmentFileVO.getFileGroupId(), attachmentFileVO.getSaveName());
        return Result.success(fileBytes);
    }


    /**
     * preview
     *
     * @return
     */
    @GetMapping("/preview")
    public Result<FileTO> preview(@RequestParam("fileId") String fileId) {
        AssertUtils.notBlank(fileId, "未找到文件");
        FileTO fileTO = new FileTO();
        AttachmentFileVO attachmentFileVO = new AttachmentFileVO();
        attachmentFileVO.setFileId(fileId);
        attachmentFileVO = attachmentFileService.loadAttachmentFile(attachmentFileVO);
        // 图片地址
        fileTO.setFilePath(attachmentFileVO.getFilePath());
        // 图片id
        fileTO.setFileId(attachmentFileVO.getFileId());
        // ext扩展
        fileTO.setFileExtName(attachmentFileVO.getFileExtName());
        return Result.success(fileTO);
    }

    /**
     * ext
     *
     * @param fileName
     * @return
     */
    private String extName(String fileName) {
        if (fileName == null) {
            return null;
        } else {
            int index = fileName.lastIndexOf(".");
            if (index == -1) {
                return "";
            } else {
                String ext = fileName.substring(index + 1);
                return !ext.contains(String.valueOf('/')) && !ext.contains(String.valueOf('\\')) ? ext : "";
            }
        }
    }
}
